package com.micai.boss.base.utils.validate;

import com.micai.boss.base.constant.ErrorCodeEnum;
import com.micai.boss.base.utils.AssertUtils;

/**
 * 描述：银行卡验证类
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/4/23 15:37
 */
public class BankCardValidator {

    /**
     * 校验银行卡卡号
     * @param cardId
     * @return
     */
    public static boolean isBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if(bit == 'N'){
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     * @param nonCheckCodeCardId
     * @return
     */
    private static char getBankCardCheckCode(String nonCheckCodeCardId){
        if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if(j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
    }

    public static Boolean  checkBankCardSame(String cardAll,String cardTop,String cardLast){
        AssertUtils.notNull(cardAll, ErrorCodeEnum.参数为空.getMessage());
        AssertUtils.notNull(cardTop, ErrorCodeEnum.参数为空.getMessage());
        AssertUtils.notNull(cardLast, ErrorCodeEnum.参数为空.getMessage());
        return cardAll.startsWith(cardTop) && cardAll.endsWith(cardLast);
    }
}
